<template>
  <div class="base-container">
    <div style="display: flex;justify-content: center;font-size: 50px;padding: 30px">
      2022年度省交通投资集团微创新成果评审项目随机分配系统
    </div>
    <div class="btn-group-inline" style="justify-content: center">
      <!-- <t-button @click="handleExtract" variant="outline" theme="primary"> -->
      <t-button @click="[extractDialog.open = true, extractDialog.loading = false]" variant="outline" theme="primary">
        <t-icon name="edit-1" slot="icon"/>
        随机分配成果
      </t-button>
      <t-button @click="handleReset" variant="outline" theme="primary">
        <t-icon name="clear" slot="icon"/>
        重置分配
      </t-button>
      <t-button @click="exportExcel" variant="outline" theme="primary">
        <t-icon name="download" slot="icon"/>
        导出
      </t-button>
    </div>
    <t-table
      id="out-table"
      rowKey="id"
      :data="data"
      bordered
      :columns="columns"
      :rowspanAndColspan="rowspanAndColspan"
      :loading="dataLoading"
      :selected-row-keys="selectedRowKeys"
      @select-change="handleSelectChange"
    >
      <template #id="{ row }">
        <div v-if="row.name!==''">{{ row.sort }}</div>
      </template>
      <template #innovationList="{ row }">
        <t-link v-if="row.name!==''" @click="dialog.header='成果列表';dialog.data=row.innovationList;dialog.open=true"
                hover="color" theme="primary">{{ row.innovationList.length }}
        </t-link>
      </template>
      <template #name="{ row: { name }}">
        {{name}}
      </template>
    </t-table>
    <review-expert-innovation-list :header="dialog.header" :data="dialog.data" :visible.sync="dialog.open"
                                   v-if="dialog.open"></review-expert-innovation-list>
    <t-dialog
      theme="warning"
      header="系统提示"
      body="是否随机为专家分配成果？"
      :visible.sync="extractDialog.open"
      :closeOnOverlayClick="false"
    >
      <template #footer>
        <t-button theme="default" @click="extractDialog.open = false">取消</t-button>
        <t-button @click="onExtractConfirm" :loading="extractDialog.loading">确定</t-button>
      </template>
    </t-dialog>
  </div>

</template>

<script>
import ReviewExpertInnovationList from "./components/review-expert-innovation-list.vue";
import FileSaver from "file-saver";
import * as XLSX from "xlsx"

export default {
  name: "review-expert-innovation",
  components: {
    ReviewExpertInnovationList
  },
  data() {
    return {
      selectedRowData:{},
      selectedRowKeys:[],
      data: [],
      dialog: {
        open: false,
        data: [],
        header: ''
      },
      extractDialog: {
        open: false,
        loading: false
      },
      dataLoading: false,
      queryParams: {
        name: '',
      },
      columns: [
        // {
        //   colKey: 'row-select',
        //   type: 'single',
        //   title: "选择",
        //   width: 64
        // },
        {
          colKey: "id",
          title: "序号",
          align: "center",
          width: 80
        },
        // {
        //   colKey: "name",
        //   title: "专家姓名",
        //   align: "center",
        //   width: 165,
        //   // ellipsis: true
        // },
        {
          colKey: "name",
          title: "专家单位",
          align: "center",
          width: 165,
          // ellipsis: true
        },
        // {
        //   colKey: "deptName",
        //   title: "工作单位",
        //   align: "center",
        //   ellipsis: true
        // },
        {
          colKey: "innovationList",
          title: "已分配成果个数",
          align: "center",
          width: 150
        },
        {
          colKey: "innovationSort",
          title: "成果编号",
          align: "center",
          width: 120
        },
        {
          colKey: "innovationName",
          title: "成果名称",
          align: "center",
          width: 220
        },
        {
          colKey: "deptName2",
          title: "申报单位",
          align: "center",
          // ellipsis: true
        },
        {
          colKey: "managerDeptName",
          title: "归口管理单位",
          align: "center",
          // ellipsis: true
        },
      ]
    }
  },
  created() {
    this.getList();
  },
  methods: {
    rowspanAndColspan({row, col, rowIndex, colIndex}) {
      if ([0, 1, 2].includes(colIndex)) {
        return {
          rowspan: row.innovationList.length,
        };
      }
    },
    getList() {
      this.dataLoading = true;
      const newData = []
      this.$api.wcx.review.otherExpertList(this.queryParams).then(
        (res) => {
          res.data.forEach((val) => {
            if (val.innovationList.length > 0) {
              newData.push({
                ...val,
                innovationName: val.innovationList[0].name,
                deptName2: val.innovationList[0].deptName,
                managerDeptName: val.innovationList[0].managerDeptName,
                innovationSort: val.innovationList[0].sort,
              })
              val.innovationList.slice(1).forEach((v) => {
                newData.push({
                  id: Number(new Date().getTime())+Number(Math.random()*10),
                  name: "",
                  deptName: "",
                  innovationList: [],
                  innovationName: v.name,
                  deptName2: v.deptName,
                  managerDeptName: v.managerDeptName,
                  innovationSort: v.sort,
                })
              })
            } else {
              newData.push(val)
            }

          })
          this.data = newData;
          this.dataLoading = false;
        }).catch((e) => {
        this.dataLoading = false;
        this.$message.error(e.toString());
      });
    },
    onExtractConfirm() {
      this.extractDialog.loading = true
      this.$api.wcx.review.otherExpertExtract().then(
        () => {
          this.getList();
          this.$message.success("分配成功");
          // 请求成功后，销毁弹框
          this.extractDialog.open = false
        }
      ).catch((e) => {
        this.extractDialog.loading = false
        this.$message.error(e.toString());
      });
    },
    handleExtract() {
      const confirmDia = this.$dialog.confirm({
        header: "系统提示",
        body: `是否随机为专家分配成果？`,
        theme: "warning",
        onConfirm: ({e}) => {
          confirmDia.update({
            confirmBtn: {
              loading: true,
            },
          })
          this.$api.wcx.review.otherExpertExtract().then(
            (res) => {
              this.getList();
              this.$message.success("分配成功");
              // 请求成功后，销毁弹框
              confirmDia.destroy();
            }
          ).catch((e) => {
            confirmDia.update({
              confirmBtn: {
                loading: false,
              },
            })
            this.$message.error(e.toString());
          });
        },
      })
    },
    // 定义导出Excel表格事件
    exportExcel() {
      /* 从表生成工作簿对象 */
      const wb = XLSX.utils.table_to_book(document.querySelector("#out-table"));
      /* 获取二进制字符串作为输出 */
      const wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
          // Blob 对象表示一个不可变、原始数据的类文件对象。
          // Blob 表示的不一定是JavaScript原生格式的数据。
          // File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
          // 返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
          new Blob([wbout], { type: "application/octet-stream" }),
          // 设置导出文件名称
          `2022年度省交通投资集团微创新成果评审项目随机分配结果_${new Date().getTime()}.xls`
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    handleReset() {
      const confirmDia = this.$dialog.confirm({
        header: "系统提示",
        body: `是否重置专家分配成果？`,
        theme: "warning",
        onConfirm: ({e}) => {
          confirmDia.update({
            confirmBtn: {
              loading: true,
            },
          })
          this.$api.wcx.review.otherExpertExtractReset().then(
            (res) => {
              this.getList();
              this.$message.success("重置成功");
              // 请求成功后，销毁弹框
              confirmDia.destroy();
            }
          ).catch((e) => {
            confirmDia.update({
              confirmBtn: {
                loading: false,
              },
            })
            this.$message.error(e.toString());
          });
        },
      })
    },
    handleSelectChange(value, { selectedRowData }) {
      this.selectedRowKeys = value;
      this.selectedRowData = selectedRowData;
    },
    handleDownload(){
      if(this.selectedRowKeys.length<=0){
        this.$message.warning("请选择一个专家");
        return false;
      }
      this.$download(`wcx/innovation/exportAllList?id=${this.selectedRowKeys[0]}`,{}, `${this.selectedRowData[0].name}_${new Date().getTime()}.xls`)
    }
  }
}
</script>
